package com.behome.common.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * HTTPRequest
 *
 * @author bh_ljy
 * @version 2024/05/07 17:59
 **/
@Slf4j
public class HTTPRequest {

    /**
     * 语音合成
     */
    public static JSONObject speechSynthesis(JSONObject param, String postUrl) {
        try {
            HttpRequest post = HttpUtil.createPost(postUrl);
            post.contentType("application/json;charset=UTF-8");
            String jsonStr = JSONUtil.toJsonStr(param);
            System.out.println(jsonStr);
            post.body(JSONUtil.toJsonStr(param));
            post.timeout(60000);
            HttpResponse httpResponse = post.execute();
            String body = httpResponse.body();
            JSONUtil.parseObj(body);
            return JSONUtil.parseObj(body);
        } catch (Exception e) {
            log.error("请求文转语服务失败!{}", e.getMessage());
            JSONObject jsonObject = new JSONObject();
            jsonObject.append("code", -1);
            return jsonObject;
        }
    }

    /**
     * @param url      请求的路径
     * @param filePath 文件将要保存的目录
     * @return java.io.File
     * @Description 从制定URL下载文件并保存到指定目录
     * @Date 2021/6/25 11:56
     * @Author Ljy
     **/
    public static Boolean download(String url, String filePath) {
        log.info("文转语下载:FilePath---->{} URL---->{}", filePath, url);
        FileOutputStream fileOut;
        HttpURLConnection conn;
        InputStream inputStream;
        try {
            // 建立链接
            URL httpUrl = new URL(url);
            conn = (HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单，默认get方式
            //conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）
            fileOut = new FileOutputStream(filePath);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while (length != -1) {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载错误，抛出异常！！");
            return false;
        }
        return true;
    }
}
